//
//  MainViewController.m
//  TY_MotorRemoteControl
//
//  Created by xiaomei su on 2018/3/2.
//  Copyright © 2018年 xuweixin. All rights reserved.
//

#import "MainViewController.h"
#import "DrawViewTool.h"
#import "CustomBelowTextView.h"
//#import "UISlider+Custom.h"
#import "XWXCustomSlider.h"
#import "BFCircleView.h"
#import "ContextDrawCircleView.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import <CoreBluetooth/CoreBluetooth.h>
#import "PlayBlueMusicListManager.h"
#import "CustomDrawView.h"
#import "MBProgressHUD+Helper.h"
#import "UIViewController+HUD.h"
#import "ShakeAlertView.h"
#import "CustomBlueListView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "NSString+extension.h"
#import "TYMBBleListView.h"

#import "TYMBTestDataView.h"


@interface MainViewController ()<UITableViewDelegate, UITableViewDataSource, ShakeAlertViewDelegate, CustomDrawViewDelegate> {
    SystemSoundID sound;
}
@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *headViewHight;
@property (weak, nonatomic) IBOutlet UIView *overspeadView;
@property (weak, nonatomic) IBOutlet XWXCustomSlider *slider;
@property (weak, nonatomic) IBOutlet UISlider *switchSlider;
@property (weak, nonatomic) IBOutlet UISlider *cutMusicSlider;
@property (weak, nonatomic) IBOutlet UIButton *lastButton;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
@property (weak, nonatomic) IBOutlet UIButton *modeButton;
@property (weak, nonatomic) IBOutlet UIButton *EQButton;
@property (weak, nonatomic) IBOutlet UIImageView *setVoiceBackImageView;
@property (weak, nonatomic) IBOutlet UIButton *subVoiceButton;
@property (weak, nonatomic) IBOutlet UIButton *addVoiceButton;
@property (weak, nonatomic) IBOutlet UIButton *outCircleButton;
@property (weak, nonatomic) IBOutlet UIButton *inCircleButton;
@property (weak, nonatomic) IBOutlet UIView *belowView;
@property (weak, nonatomic) IBOutlet UILabel *modelLabel;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIImageView *greenImageView;
@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;
@property (nonatomic, strong) BFCircleView *circleView;
@property (nonatomic, strong) ContextDrawCircleView *contextCircleView;
@property (weak, nonatomic) IBOutlet UISlider *timeSlider;
@property (weak, nonatomic) IBOutlet UIButton *setButton;
@property (weak, nonatomic) IBOutlet UIView *setShowView;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIButton *disconnectButton;
@property (weak, nonatomic) IBOutlet UIButton *backgroundButton;
@property (weak, nonatomic) IBOutlet UIButton *blueListButton;
@property (weak, nonatomic) IBOutlet UILabel *stateLabel;
@property (weak, nonatomic) IBOutlet UIView *powerOffOverspeadView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *belowViewWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *belowViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *outCircleHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *outCircleWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inCircleWidth;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *inCircleHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *belowHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *switchHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *switchTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *changeTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buttonTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *EQButtonTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *playTimeViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *subButtonBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *subButtonLeading;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addButtonBottom;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addButtonTrailing;
@property (weak, nonatomic) IBOutlet UIButton *sliderPretetionBtn;
@property (nonatomic, strong) XWXCustomSlider *textSlider;
@property (nonatomic, strong) CustomBelowTextView *belowDrawView;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) NSInteger sliderValue;// 记录headSlider value
@property (nonatomic, assign) CGFloat switchSliderValue;// 记录switchSlider value
@property (nonatomic, assign) CGFloat cutSliderValue;//记录切歌sliderValue
@property (nonatomic, assign) NSInteger voiceValue;
@property (nonatomic, strong) UIBezierPath *trackPath;
@property (nonatomic, strong) CAShapeLayer *trackLayer;
@property (nonatomic, strong) CAShapeLayer *progressLayer;
@property (nonatomic, strong) UIBezierPath *progressPath;
//@property (nonatomic, strong) NSMutableArray *blueArray;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, strong) NSMutableArray *currentMusicArray;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger currentMusicTime;
@property (nonatomic, assign) NSInteger currentMusicNumber;
@property (nonatomic, strong) CustomDrawView *drawView;
//@property (nonatomic, assign) BOOL isHandControl;
//振动计时器
@property (nonatomic,strong)NSTimer *vibrationTimer;
@property (nonatomic, strong) UIAlertController *shakeAterVC;
@property (nonatomic, strong) ShakeAlertView *shakeView;

@property (strong, nonatomic) MPMusicPlayerController *musicPlayerController; //音乐播放器

/// 20231128新增
/// 防盗开关
@property (nonatomic, assign) BOOL antiTheftSwitch;
/// 设备开关
@property (nonatomic, assign) BOOL deviceSwitch;

@property (weak, nonatomic) IBOutlet UIView *musicSecondBgV;
@property (weak, nonatomic) IBOutlet UIButton *switchSliderProtectionBtn;

@end

@implementation MainViewController
//void SetAudioServicesStopSystemSound(int);
//void AudioServicesPlaySystemSoundWithVibration(int, id, NSDictionary *);

- (TYMBHeadSliderView *)tyLockHeadV {
    
    if (!_tyLockHeadV) {
        _tyLockHeadV = [[TYMBHeadSliderView alloc]init];
        [self.testSliderContentV addSubview:_tyLockHeadV];
    }
    return _tyLockHeadV;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initForUI];
    [self backViewShow];
    [self addNotification];
    
    [self.tyLockHeadV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.right.mas_equalTo(0);

    }];
}

- (void)addBleAlertView {
    UIView *view = [self.view viewWithTag:90582];
    if (!view) {
        TYMBBleListView *listV = [[[NSBundle mainBundle]loadNibNamed:@"TYMBBleListView" owner:nil options:nil]lastObject];
        listV.tag = 90582;
        listV.frame = self.view.bounds;
        [self.view addSubview:listV];
    }
    
    
}

/// 添加Notification
- (void)addNotification {
    [Notification_center addObserver:self selector:@selector(notificationHandle:) name:BLE_SCAN_UPDATE_NOTIFICATION object:nil];
    [Notification_center addObserver:self selector:@selector(notificationHandle:) name:BLE_CONNECTED_SUCCESS_NOTIFICATION object:nil];
    [Notification_center addObserver:self selector:@selector(notificationHandle:) name:BLE_DISCONNECTED_FAIL_NOTIFICATION object:nil];
    [Notification_center addObserver:self selector:@selector(notificationHandle:) name:BLE_RECEIVE_DATA_NOTIFICATION object:nil];
    [Notification_center addObserver:self selector:@selector(notificationHandle:) name:BLE_CHARACTERISTIC_OPEN_NOTI object:nil];
    [Notification_center addObserver:self selector:@selector(appEnterForegroundHandleEven) name:@"appEnterForeground" object:nil];
    [Notification_center addObserver:self selector:@selector(addBleAlertView) name:BLE_UNCONNECTED_DEVICE_NOTIFICATION object:nil];

}

- (void)notificationHandle:(NSNotification *)notification {
    NSString *dataString = notification.object;
    if ([notification.name isEqualToString:BLE_SCAN_UPDATE_NOTIFICATION]) {
        
    }else if ([notification.name isEqualToString:BLE_CONNECTED_SUCCESS_NOTIFICATION]) {
        [self bleConnectedSuccessHandle];
    }else if ([notification.name isEqualToString:BLE_DISCONNECTED_FAIL_NOTIFICATION]) {
        [self bleDisconnectedHandle];
    }else if ([notification.name isEqualToString:BLE_RECEIVE_DATA_NOTIFICATION]) {
        [self receiveDataHandleWith:dataString];
    }else if ([notification.name isEqualToString:BLE_CHARACTERISTIC_OPEN_NOTI]) {
        [self bleOpenChaSuccessHandle];
    }
    
}

//开始响铃及振动
-(void)startShakeSound{
  
//       NSString *path = [[NSBundle mainBundle] pathForResource:@"2125" ofType:@"wav"];
//       AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &sound);
       AudioServicesAddSystemSoundCompletion(sound, NULL, NULL, soundCompleteCallback, NULL);
       AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
       AudioServicesPlaySystemSound(sound);
  
  
       /**
        28      初始化计时器  每一秒振动一次
        29
        30      @param playkSystemSound 振动方法
        31      @return
        32      */
       _vibrationTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(playkSystemSound) userInfo:nil repeats:YES];
   }
//振动
 - (void)playkSystemSound{
         AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
 }
 //停止响铃及振动
-(void)stopShakeSound{
   
        [_vibrationTimer invalidate];
        AudioServicesRemoveSystemSoundCompletion(sound);
        AudioServicesDisposeSystemSoundID(sound);
   
}
 //响铃回调方法
 void soundCompleteCallback(SystemSoundID sound,void * clientData) {
        AudioServicesPlaySystemSound(sound);
   
 }

-(void)shakeViewShow{
    self.shakeView.hidden = NO;
}

-(void)ShakeAlertViewUnlockClickEven{
    self.slider.value = 0;
    self.sliderValue = 0;
    [BLE_MAN sendDataWithCommand:@"00030a" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        if (!result) {
            [self addBleAlertView];
        }
    }];
//    self.overspeadView.hidden = YES;
    self.shakeView.hidden = YES;
}

-(void)appEnterForegroundHandleEven{
    BLE_MAN.isHandControl = NO;
    if (BLE_MAN.peripheral != nil && BLE_MAN.peripheral.state != CBPeripheralStateDisconnected) {
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
        
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [self autoConnectPeripheral];
            
        });
    }
}

-(void)initForUI{
    self.musicPlayerController = [MPMusicPlayerController applicationMusicPlayer];
    
    
    self.stateLabel.text = NSLocalizedString(@"DisConnect",@"未连接");
    self.height = self.view.frame.size.height;
    self.width = self.view.frame.size.width;
    
    self.belowViewWidth.constant = self.height*0.38;
    self.belowViewHeight.constant = self.height*0.38;
    self.outCircleWidth.constant = self.height*0.38*0.8;
    self.outCircleHeight.constant = self.height*0.38*0.8;
    self.inCircleHeight.constant = self.height*0.38*0.8*0.9;
    self.inCircleWidth.constant = self.height*0.38*0.8*0.9;
    self.belowHeight.constant = self.height*0.06;
    self.switchHeight.constant = self.height * 0.05;
    self.changViewHeight.constant = self.height *0.05;
    self.switchTop.constant = self.height*0.04;
    self.changeTop.constant = self.height *0.04;
    self.buttonTop.constant = self.height *0.04;
    self.EQButtonTop.constant = self.height *0.04;
    self.playTimeViewHeight.constant = self.height *0.05;
    self.subButtonBottom.constant = self.height*0.30 *0.07;
    self.subButtonLeading.constant = self.height*0.30 *0.095;
    self.addButtonBottom.constant = self.height*0.30 *0.07;
    self.addButtonTrailing.constant = self.height*0.30 *0.095;
    self.headViewHight.constant = self.height *235/1280;
//    [self drawViewEven];
    [self initSlider];
    
    self.sliderValue = 0;
    self.switchSliderValue = 0;
    self.cutSliderValue = 0.5;
    self.voiceValue = 0;
    self.setVoiceBackImageView.userInteractionEnabled = YES;
    
    self.setShowView.layer.cornerRadius = 20;
    self.setShowView.layer.masksToBounds = YES;
    
    self.drawView = [[CustomDrawView alloc]initWithFrame:CGRectMake(0, 0, self.height*0.38, self.height*0.38)];
    self.drawView.delegate = self;
    [self.belowView insertSubview:self.drawView aboveSubview:self.setVoiceBackImageView];
//    [self.belowView insertSubview:self.drawView belowSubview:self.setShowView];

    //点击手势
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(singleTapImageViewHandle:)];
    singleTap.numberOfTapsRequired = 1;
    [self.drawView addGestureRecognizer:singleTap];
    
    UIPanGestureRecognizer *panGR = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panGestureRecognizerHandleAction:)];
    
    
    //长按手势
    UILongPressGestureRecognizer *longPGR = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPGRAction:)];
    longPGR.minimumPressDuration = 1;
    [self.inCircleButton addGestureRecognizer:longPGR];
}
-(void)setShakeTimeWith:(int)mSecond{
    [self stopShakeSound];
    [self startShakeSound];
    int64_t delayInSeconds = mSecond;      // 延迟的时间
    /*
     *@parameter 1,时间参照，从此刻开始计时
     *@parameter 2,延时多久，此处为秒级，还有纳秒等。10ull * NSEC_PER_MSEC
     */
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_MSEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [self stopShakeSound];
    });
}
//type  1:验证密码     2：修改密码
-(void)textAlertViewSHow:(NSString *)password type:(NSInteger )type{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"WarmTips",@"温馨提示") message:password preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancle",@"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    //增加确定按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Sure",@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //获取第1个输入框；
        UITextField *userNameTextField = alertController.textFields.firstObject;
        NSString *password = userNameTextField.text;
        self.password = password;
        NSMutableString *sixteenPassword = [NSMutableString string];
        if (type == 1) {
            [sixteenPassword appendString:@"0701"];
        }else{
            [sixteenPassword appendString:@"0702"];
        }
        if (password.length > 1) {
            for (NSInteger i = 0; i < password.length; i ++) {
                NSString *singer = [password subStringWithRangeForNil:NSMakeRange(i, 1)];
                [sixteenPassword appendString:[CalculateTool getHexByDecimal:singer.integerValue]];
                
            }
        }
        [BLE_MAN sendDataWithCommand:sixteenPassword withBlock:^(BOOL result, NSString * _Nullable resultStr) {
            
        }];
        NSLog(@"支付密码 = %@",sixteenPassword);
        
    }]];
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = NSLocalizedString(@"writePwd",@"请输入四位数密码");
        textField.keyboardType = UIKeyboardTypeNumberPad;
        
        textField.secureTextEntry = YES;
        
    }];
    [self presentViewController:alertController animated:true completion:nil];
}

-(void)tipsAlertSelectViewSHow:(NSString *)tips peripheralName:(NSString *)peripheralName{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"WarmTips",@"温馨提示") message:tips preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancle",@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Sure",@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self savePassword:self.password peripheralName:peripheralName];

    }]];
    [self presentViewController:alertController animated:true completion:nil];

}

-(void)showInfoMessage:(NSString *)message{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"WarmTips",@"温馨提示") message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Sure",@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertController animated:true completion:nil];

}



-(void)singleTapImageViewHandle:(UITapGestureRecognizer *)tap{
    CGPoint tapPoint = [tap locationInView:self.setVoiceBackImageView];
    CGFloat distance = [self calculationDistanceBewteenTwoPints:tapPoint andPoint2:CGPointMake(120, 120)];
    NSLog(@"%f",distance);
    
    CGFloat angle = [self getAnglesWithThreePoint:tapPoint pointB:CGPointMake(120, 120) pointC:CGPointMake(0, 120)];
    if (tapPoint.y > 120 && tapPoint.x < 120) {
        
    }else{
        angle = angle + M_PI_4;

    }
    NSInteger value = angle *10 /M_PI;
    NSLog(@"%f",angle);
    NSLog(@"%ld",value);
    if (value>14) {
        value = 14;
    }
    [BLE_MAN sendDataWithCommand:[@"0002" stringByAppendingString:[CalculateTool getHexByDecimal:value]] withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        if (!result) {
            [self addBleAlertView];
        }
    }];

}
#pragma mark - drawView滑动
-(void)CustomDrawViewMoveLocation:(CGPoint)locationPoint{
    if (locationPoint.y > CGRectGetMinY(self.addVoiceButton.frame)+10) {
        return;
    }
    CGFloat angle = [self getAnglesWithThreePoint:locationPoint pointB:CGPointMake(120, 120) pointC:CGPointMake(0, 120)];
    if (locationPoint.y > 120 && locationPoint.x < 120) {
        
    }else{
        angle = angle + M_PI_4;
        
    }
    NSLog(@"addBUtton%f%f",self.addVoiceButton.frame.origin.x,self.addVoiceButton.frame.origin.y);
    NSInteger value = angle *10 /M_PI;
    NSLog(@"angle%f",angle);
    NSLog(@"value%ld",value);
    if (value<=15) {
        value = 15;
    }
    
}
-(void)CustomDrawViewMoveEndLocation:(CGPoint)locationPoint{
    if (locationPoint.y > CGRectGetMinY(self.addVoiceButton.frame)) {
        return;
    }
    CGFloat angle = [self getAnglesWithThreePoint:locationPoint pointB:CGPointMake(120, 120) pointC:CGPointMake(0, 120)];

    if (locationPoint.y > 120 && locationPoint.x < 120) {
        
    }else{
        angle = angle + M_PI_4;
        
    }
    NSInteger value = angle *10 /M_PI;
    NSLog(@"%f",angle);
    NSLog(@"%ld",value);
    if (value>15) {
        value = 15;
    }
    [BLE_MAN sendDataWithCommand:[@"0002" stringByAppendingString:[CalculateTool getHexByDecimal:value]] withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        [self addBleAlertView];
    }];
}

-(void)setVoiceImageWithValue:(NSInteger)value{
    [self.drawView testWithNumber:value];
}

-(void)singleTapBackClearViewHandle:(UITapGestureRecognizer *)singerTap{
    [self backViewHidden];
}

-(CGFloat)getAnglesWithThreePoint:(CGPoint)pointA pointB:(CGPoint)pointB pointC:(CGPoint)pointC {
    CGPoint Xpoint = CGPointMake(pointA.x + 100, pointA.y);
    CGFloat a = pointB.x - pointA.x;
    CGFloat b = pointB.y - pointA.y;
    CGFloat c = Xpoint.x - pointA.x;
    CGFloat d = Xpoint.y - pointA.y;
    CGFloat rads = acos(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d))));
    if (pointA.y>pointB.y) {
        if (pointA.x > pointB.x) {
            rads = 2*M_PI-rads;
        }
    }
    return rads;
    
}

-(CGFloat)calculationDistanceBewteenTwoPints:(CGPoint)point1 andPoint2:(CGPoint)point2{
    CGFloat deltaX = point1.x - point2.x;
    CGFloat deltaY = point1.y - point2.y;
    return sqrt(deltaX *deltaX + deltaY *deltaY);
}

-(void)drawViewEven{
    self.belowDrawView = [[CustomBelowTextView alloc]initWithFrame:CGRectMake((self.width-210)/2, self.headViewHight.constant-40, 210, 20)];
    [self.headView addSubview:self.belowDrawView];
}

-(void)initSlider{
    
    UIImage *maxImage = [UIImage imageNamed:@"logo_bg_green"];
    UIImage *minImage = [UIImage imageNamed:@"logo_bg_red"];
    minImage = [minImage scaleToSize:CGSizeMake(200, 4)];
    maxImage = [maxImage scaleToSize:CGSizeMake(200, 4)];
    [self.slider setMinimumTrackImage:minImage forState:UIControlStateNormal];
    [self.slider setMaximumTrackImage:maxImage forState:UIControlStateNormal];
    UIImage *sliderImage = [UIImage imageNamed:@"logo"];
    sliderImage = [sliderImage scaleToSize:CGSizeMake(self.height*0.21214393, self.height*0.10494753)];
    [self.slider setThumbImage:sliderImage forState:UIControlStateNormal];
    self.slider.continuous = NO;
    
    UIImage *switchThumImg = [UIImage imageNamed:@"Switches"];
    switchThumImg = [switchThumImg scaleToSize:CGSizeMake(42, 28.2)];
    [self.switchSlider setThumbImage:switchThumImg forState:UIControlStateNormal];
    self.switchSlider.continuous = NO;
    
    UIImage *cutThumImg = [UIImage imageNamed:@"Switching"];
    cutThumImg = [cutThumImg scaleToSize:CGSizeMake(42, 28.2)];
    [self.cutMusicSlider setThumbImage:cutThumImg forState:UIControlStateNormal];
    self.cutMusicSlider.continuous = NO;
    
    UIImage *timeThumPic = [UIImage imageWithColor:[UIColor greenColor] size:CGSizeMake(5, 5)];
    [self.timeSlider setThumbImage:[timeThumPic circleImage] forState:UIControlStateNormal];

    
}

-(BOOL)backViewShow{
    
    NSLog(@"%@",BLE_MAN.peripheral);
    if (BLE_MAN.peripheral == nil) {
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));

            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self autoConnectPeripheral];
                
            });
            
        
        [BLE_MAN startScanAction];

        [UIView animateWithDuration:5 animations:^{
            self.slider.value = 0;
            self.sliderValue = 0;
            self.switchSlider.value = 0;
            self.switchSliderValue = 0;
            self.cutMusicSlider.value = 0.5;
            self.cutSliderValue = 0.5;
        }];
        
        
        return  NO;
    }else{
        if (BLE_MAN.peripheral.state != CBPeripheralStateConnected) {
            [BLE_MAN startScanAction];

            
            [UIView animateWithDuration:5 animations:^{
                self.slider.value = 0;
                self.sliderValue = 0;
                self.switchSlider.value = 0;
                self.switchSliderValue = 0;
                self.cutMusicSlider.value = 0.5;
                self.cutSliderValue = 0.5;
            }];
            return NO;
        }
    }
    
    return NO;
    
}
-(void)backViewHidden{

}

-(void)currentMusicHandleTimeEven{
    self.currentMusicTime ++;
    self.timeSlider.value = self.currentMusicTime;
    self.startTimeLabel.text = [CalculateTool secondToMiniuteSecondString:self.currentMusicTime];
}

//画两个圆形
-(void)createBezierPath:(CGRect)mybound
{
    CGFloat width = (self.width -80)/2;
    CGPoint centerPoint = CGPointMake(self.width/2, self.height-self.width/2);
    //外圆
    _trackPath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:width startAngle:M_PI/4*3 endAngle:M_PI_4 clockwise:YES];;
    
    _trackLayer = [CAShapeLayer new];
    [self.view.layer addSublayer:_trackLayer];
    _trackLayer.fillColor = nil;
    _trackLayer.strokeColor=[UIColor grayColor].CGColor;
    _trackLayer.path = _trackPath.CGPath;
    _trackLayer.lineWidth=5;
    _trackLayer.frame = mybound;
    
    //内圆
    _progressPath = [UIBezierPath bezierPathWithArcCenter:centerPoint radius:(mybound.size.width - 0.7)/ 2 startAngle:- M_PI_2 endAngle:(M_PI * 2) * 0.7 - M_PI_2 clockwise:YES];
    _progressLayer = [CAShapeLayer new];
    [self.view.layer addSublayer:_progressLayer];
    _progressLayer.fillColor = nil;
    _progressLayer.strokeColor=[UIColor redColor].CGColor;
    _progressLayer.lineCap = kCALineCapRound;
    _progressLayer.path = _progressPath.CGPath;
    _progressLayer.lineWidth=5;
    _progressLayer.frame = mybound;
}
-(void)savePassword:(NSString *)password peripheralName:(NSString *)peripheralName{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableArray *array = [NSMutableArray array];
    NSArray *oldArray = [self getUserDefaultDeviceAndPasswordArray];
    [array addObjectsFromArray:[self getUserDefaultDeviceAndPasswordArray]];
    BOOL result = NO;
    for (NSDictionary *dict in oldArray) {
        if ([dict[@"name"] isEqualToString:peripheralName]) {
            result = YES;
            if ([array containsObject:dict]) {
                [array removeObject:dict];
                [array addObject:@{@"name":peripheralName,@"password":password}];
            }
        }
    }
    if (result == NO) {
        [array addObject:@{@"name":peripheralName,@"password":password}];
    }
    [userDefaults removeObjectForKey:PASSWORD_KEY];
    [userDefaults setObject:array forKey:PASSWORD_KEY];
    [userDefaults synchronize];
}

-(NSArray *)getUserDefaultDeviceAndPasswordArray{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    return [userDefaults objectForKey:PASSWORD_KEY];
}

-(NSString *)getUserDefaultPassword:(NSString *)peripheralName{
    NSArray *array = [self getUserDefaultDeviceAndPasswordArray];
    NSDictionary *dict;
    for (NSDictionary *dic in array) {
        if ([dic[@"name"] isEqualToString:peripheralName]) {
            dict = dic;
        }
    }
    if (dict.count > 0) {
        return dict[@"password"];
    }
    return @"";
}

-(BOOL)judePasswordWithKey:(NSString *)peripheralName{
    NSString *string = [self getUserDefaultPassword:peripheralName];
    if (string.length > 0) {
        return YES;
    }
    return NO;
}

- (IBAction)sliderAction:(UISlider *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if (self.switchSliderValue == 0) {
        if (sender.value > self.sliderValue) {
            sender.value = 1;
            self.sliderValue = 1;
            [BLE_MAN sendDataWithCommand:@"000309" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
                
            }];
//            self.overspeadView.hidden = NO;
            
        }else{
            sender.value = 0;
            self.sliderValue = 0;
            [BLE_MAN sendDataWithCommand:@"00030a" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
                
            }];
//            self.overspeadView.hidden = YES;
        }
    }else{
       
    }
}

- (IBAction)sliderTouchBeginAction:(XWXCustomSlider *)sender {
    NSLog(@"11112222");
    sender.userInteractionEnabled = YES;


}

- (IBAction)sliderTouchDownAction:(XWXCustomSlider *)sender {
    NSLog(@"000098888");
    if (self.switchSliderValue != 0) {
        sender.userInteractionEnabled = NO;
    }
}

- (IBAction)sliderProtectionBtnClicked:(UIButton *)sender {
    
    if (BLE_MAN.peripheral && BLE_MAN.peripheral.state == CBPeripheralStateConnected) {
        [self showHUDWith:NSLocalizedString(@"shutDown",@"请先关机") showView:[UIApplication sharedApplication].keyWindow];
    }else {
        [self showHUDWith:NSLocalizedString(@"BlueToothDisConnect",@"请先关机") showView:[UIApplication sharedApplication].keyWindow];

    }
    
    
}

- (IBAction)switchSliderProtectionBtnCLicked:(UIButton *)sender {
}

- (IBAction)switchSliderAction:(UISlider *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }

    [self setShakeTimeWith:300];
    BOOL isSend;
    if (sender.value >= self.switchSliderValue) {
        if (sender.value - self.switchSliderValue > 0.5) {
            isSend = YES;
            
        }else{
            isSend = NO;
        }
    }else{
        if (self.switchSliderValue - sender.value > 0.5) {
            isSend = YES;
        }else{
            isSend = NO;
        }
    }
//    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if (isSend) {
        if (self.switchSliderValue == 1) {
            sender.value = 0;
            self.switchSliderValue = 0;
//            self.sliderPretetionBtn.hidden = YES;
            UIImage *switchThumImg = [UIImage imageNamed:@"Switches"];
            switchThumImg = [switchThumImg scaleToSize:CGSizeMake(42, 28.2)];
            [self.switchSlider setThumbImage:switchThumImg forState:UIControlStateNormal];
            [BLE_MAN sendDataWithCommand:@"000308" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
                
            }];
            self.powerOffOverspeadView.hidden = NO;
        }else{
            sender.value = 1;
            self.switchSliderValue = 1;
//            self.sliderPretetionBtn.hidden = NO;
            UIImage *switchThumImg = [UIImage imageNamed:@"Switches_pre"];
            switchThumImg = [switchThumImg scaleToSize:CGSizeMake(42, 28.2)];
            [self.switchSlider setThumbImage:switchThumImg forState:UIControlStateNormal];
            [BLE_MAN sendDataWithCommand:@"000308" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
                
            }];
            self.powerOffOverspeadView.hidden = YES;
        }
    }else{
        sender.value = self.switchSliderValue;
    }
}
- (IBAction)cutSliderAction:(UISlider *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if (sender.value > self.cutSliderValue) {
        sender.value = 1;
        self.cutSliderValue = 1;
        self.nextButton.selected = YES;
        self.lastButton.selected = NO;
        [BLE_MAN sendDataWithCommand:@"000303" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
            
        }];
    }else{
        sender.value = 0;
        self.cutSliderValue = 0;
        self.nextButton.selected = NO;
        self.lastButton.selected = YES;
        [BLE_MAN sendDataWithCommand:@"000301" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
            
        }];
    }
    __block MainViewController *weakSelf = self;
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 1.0*NSEC_PER_SEC);
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        weakSelf.cutMusicSlider.value = 0.5;
        weakSelf.cutSliderValue = 0.5;
        self.nextButton.selected = NO;
        self.lastButton.selected = NO;
    });

}
- (IBAction)lastButtonAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    self.cutSliderValue = 0;
    self.cutMusicSlider.value = 0;
    self.nextButton.selected = NO;
    self.lastButton.selected = YES;
    [BLE_MAN sendDataWithCommand:@"000301" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];
    __block MainViewController *weakSelf = self;
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 1.0*NSEC_PER_SEC);
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        weakSelf.cutMusicSlider.value = 0.5;
        weakSelf.cutSliderValue = 0.5;
        self.nextButton.selected = NO;
        self.lastButton.selected = NO;
    });
}
- (IBAction)nextButtonAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    self.cutSliderValue = 1;
    self.cutMusicSlider.value = 1;
    self.nextButton.selected = YES;
    self.lastButton.selected = NO;
    __block MainViewController *weakSelf = self;
    [BLE_MAN sendDataWithCommand:@"000303" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];
    dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, 1.0*NSEC_PER_SEC);
    dispatch_after(delayTime, dispatch_get_main_queue(), ^{
        weakSelf.cutMusicSlider.value = 0.5;
        weakSelf.cutSliderValue = 0.5;
        self.nextButton.selected = NO;
        self.lastButton.selected = NO;
    });

}
- (IBAction)modeButtonAction:(UIButton *)sender {
    
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    [self.timer invalidate];
    [BLE_MAN sendDataWithCommand:@"000306" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];

}
- (IBAction)EQButtonAction:(UIButton *)sender {
 
    
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    [BLE_MAN sendDataWithCommand:@"000307" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];

}
- (IBAction)inButtonAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    [BLE_MAN sendDataWithCommand:@"000302" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
}
- (IBAction)outButtonAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    [BLE_MAN sendDataWithCommand:@"000302" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
- (IBAction)subVoiceButtonAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    if (self.voiceValue > 0) {
        self.voiceValue --;
    }
    [BLE_MAN sendDataWithCommand:[@"0002" stringByAppendingString:[CalculateTool getHexByDecimal:self.voiceValue]] withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];
}
- (IBAction)addVoiceButtonAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    if (self.voiceValue < 15) {
        self.voiceValue ++;
    }
    [self setShakeTimeWith:300];
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    [BLE_MAN sendDataWithCommand:[@"0002" stringByAppendingString:[CalculateTool getHexByDecimal:self.voiceValue]] withBlock:^(BOOL result, NSString * _Nullable resultStr) {
        
    }];
}
- (IBAction)modifyPasswordAction:(UIButton *)sender {
//    [self sendData:@"FFF0" chaUUID:@"FFF1" command:@"0704"];
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self textAlertViewSHow:NSLocalizedString(@"writePwd",@"请输入四位数密码") type:2];
}

- (IBAction)codeButtonClickedAction:(UIButton *)sender {
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    [self setShakeTimeWith:300];
    [self textAlertViewSHow:NSLocalizedString(@"writePwd",@"请输入四位数密码") type:2];
    
    self.setShowView.hidden = !self.setShowView.hidden;
    self.backgroundButton.hidden = !self.backgroundButton.hidden;
//    self.drawView.userInteractionEnabled = self.setShowView.hidden;
}
- (IBAction)disconnectButtonClickAction:(UIButton *)sender {
    BLE_MAN.isHandControl = YES;
    self.setShowView.hidden = !self.setShowView.hidden;
    self.backgroundButton.hidden = !self.backgroundButton.hidden;
    if (BLE_MAN.peripheral != nil) {
        if (BLE_MAN.peripheral.state == CBPeripheralStateConnected) {
            [BLE_MAN disConnectedBleWith:BLE_MAN.peripheral];
        }
    }
}
- (IBAction)backgroundButtonCLickAction:(UIButton *)sender {
    self.setShowView.hidden = !self.setShowView.hidden;
    self.backgroundButton.hidden = !self.backgroundButton.hidden;
}
- (IBAction)blueListButtonClickAction:(UIButton *)sender {
    [self addBleAlertView];
}

- (IBAction)setButtonClickAction:(UIButton *)sender {
    self.setShowView.hidden = !self.setShowView.hidden;
    self.backgroundButton.hidden = !self.backgroundButton.hidden;
}
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"震动开始");
}
-(void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event{
    NSLog(@"震动结束");
}
// 长按手势
-(void)longPGRAction:(UILongPressGestureRecognizer *)longPGR{
    BOOL result = [self backViewShow];
    if (result) {
        return;
    }
    if (longPGR.state == UIGestureRecognizerStateEnded) {
        NSLog(@"长按了");
        [BLE_MAN sendDataWithCommand:[@"00030b" stringByAppendingString:[CalculateTool getHexByDecimal:self.voiceValue]] withBlock:^(BOOL result, NSString * _Nullable resultStr) {
            
        }];

    }
}

#pragma mark - delegateMethod


-(void)autoConnectPeripheral{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *identifier = [userDefaults objectForKey:UD_FOR_LAST_CONNECTED_IDENTIFI];
    NSUUID *uuidID = [[NSUUID alloc]initWithUUIDString:identifier];
    if (identifier.length > 0) {
        NSArray *arrays = [BLE_MAN.centerManager retrievePeripheralsWithIdentifiers:@[uuidID]];
        NSLog(@"%@",arrays);
        for (CBPeripheral *peripheral in arrays) {
            //        if ([identifier isEqualToString:peripheral.identifier.UUIDString]) {
            [self showLoadingHUD:NSLocalizedString(@"connecting",@"正在连接") showView:[UIApplication sharedApplication].keyWindow];
            [BLE_MAN connectBleWith:peripheral];
            dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0/*延迟执行时间*/ * NSEC_PER_SEC));
            dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                [self hideHUD:[UIApplication sharedApplication].keyWindow];
            });
            break;
        }
    }
    
}
#pragma mark - customBlueListViewDelegate
-(void)CustomBlueListViewCloseButtonClickAction{
    [self backViewHidden];
}
-(void)CustomBlueListViewStopScanButtonClickAction{
    NSLog(@"停止搜索");
}




-(ShakeAlertView *)shakeView{
    if (!_shakeView) {
        _shakeView = [[[NSBundle mainBundle]loadNibNamed:@"ShakeAlertView" owner:nil options:nil]lastObject];
        _shakeView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        _shakeView.hidden = YES;
        _shakeView.delegate = self;
        [self.view addSubview:_shakeView];
    }
    return _shakeView;
}


-(NSMutableArray *)currentMusicArray{
    if (!_currentMusicArray) {
        _currentMusicArray = [NSMutableArray array];
    }
    return _currentMusicArray;
}


- (void)bleScanHanle {
    
}

- (void)bleConnectedSuccessHandle {
    [self backViewHidden];
    self.stateLabel.text = NSLocalizedString(@"Connected",@"已连接");

}

- (void)bleDisconnectedHandle {
    self.stateLabel.text = NSLocalizedString(@"DisConnect",@"未连接");
    self.musicSecondBgV.hidden = YES;


}

- (void)bleOpenChaSuccessHandle {
    NSString *savePwd = [self getUserDefaultPassword:BLE_MAN.peripheral.name];
    if (savePwd.length > 0 ) {
        self.password = savePwd;
        NSMutableString *sixteenPassword = [NSMutableString string];
        [sixteenPassword appendString:@"0701"];
        
        for (NSInteger i = 0; i < savePwd.length; i ++) {
            NSString *singer = [savePwd subStringWithRangeForNil:NSMakeRange(i, 1)];
            [sixteenPassword appendString:[CalculateTool getHexByDecimal:singer.integerValue]];
            
        }
        [BLE_MAN sendDataWithCommand:sixteenPassword withBlock:^(BOOL result, NSString * _Nullable resultStr) {
            
        }];
    }else{
        if (self.password.length > 0) {
            NSMutableString *sixteenPassword = [NSMutableString string];
            [sixteenPassword appendString:@"0701"];
            
            for (NSInteger i = 0; i < self.password.length; i ++) {
                NSString *singer = [self.password subStringWithRangeForNil:NSMakeRange(i, 1)];
                [sixteenPassword appendString:[CalculateTool getHexByDecimal:singer.integerValue]];
                
            }
            [BLE_MAN sendDataWithCommand:sixteenPassword withBlock:^(BOOL result, NSString * _Nullable resultStr) {
                
            }];
        }
        [self textAlertViewSHow:NSLocalizedString(@"writePwd",@"请输入四位数密码") type:1];
    }
}

- (void)receiveDataHandleWith:(NSString *)dataString {
    NSLog(@"收到的数据：%@",dataString);
    NSString *firstByte = [dataString subStringWithRangeForNil:NSMakeRange(0, 2)];
    if ([firstByte isEqualToString:@"00"]) {
        NSString *secondByte = [dataString subStringWithRangeForNil:NSMakeRange(2, 2)];
        if ([secondByte isEqualToString:@"01"]) {
            //工作模式
            [self.timer invalidate];
            self.timeSlider.value = 0;
            self.startTimeLabel.text = @"00:00";
            self.endTimeLabel.text = @"00:00";
            self.messageLabel.text = @"";
            NSString *thirdByte = [dataString subStringWithRangeForNil:NSMakeRange(4, 2)];
            self.switchSlider.value = 1;
            self.switchSliderValue = 1;
            self.powerOffOverspeadView.hidden = YES;
            self.slider.value = 0;
            self.sliderValue = 0;
            [self stopShakeSound];
            UIImage *switchThumImg = [UIImage imageNamed:@"Switches_pre"];
            switchThumImg = [switchThumImg scaleToSize:CGSizeMake(42, 28.2)];
            [self.switchSlider setThumbImage:switchThumImg forState:UIControlStateNormal];
            
            if ([thirdByte isEqualToString:@"04"]) {
                self.musicSecondBgV.hidden = NO;
            }else {
                self.musicSecondBgV.hidden = YES;
            }
            
            if ([thirdByte isEqualToString:@"01"]) {
                // FM
                //                    [self.timer invalidate];
                self.modelLabel.text = @"FM";
            }
            if ([thirdByte isEqualToString:@"02"]) {
                // AUX
                self.modelLabel.text = @"AUX";
                self.messageLabel.text = @"";
            }
            if ([thirdByte isEqualToString:@"03"]) {
                // BT
                self.outCircleButton.selected = YES;
                self.modelLabel.text = @"BT";
                self.messageLabel.text = @"";
                if ([[AVAudioSession sharedInstance] isOtherAudioPlaying]) {
                    NSLog(@"正在播放");
                    self.outCircleButton.selected = YES;
                    self.inCircleButton.selected = YES;
                }else{
                    NSLog(@"暂停播放");
                    self.outCircleButton.selected = NO;
                    self.inCircleButton.selected = NO;
                }
            }
            if ([thirdByte isEqualToString:@"04"]) {
                // MUSIC
                NSString *fourByte = [dataString subStringWithRangeForNil:NSMakeRange(6, 2)];
                if ([fourByte isEqualToString:@"00"]) {
                    // SDMMC
                    self.modelLabel.text = @"SDMMC";
                    
                }
                if ([fourByte isEqualToString:@"01"]) {
                    // USB
                    self.modelLabel.text = @"USB";
                    
                }
                
            }
            if ([thirdByte isEqualToString:@"05"]) {
                // POWEROFF
                self.switchSliderValue = 0;
                self.switchSlider.value = 0;
                self.slider.value = 0;
                self.sliderValue = 0;
                self.powerOffOverspeadView.hidden = NO;
                UIImage *switchThumImg = [UIImage imageNamed:@"Switches"];
                switchThumImg = [switchThumImg scaleToSize:CGSizeMake(42, 28.2)];
                [self.timer invalidate];
                [self.switchSlider setThumbImage:switchThumImg forState:UIControlStateNormal];
            }
            if ([thirdByte isEqualToString:@"06"]) {
                // 防盗
                self.switchSlider.value = 0;
                self.switchSliderValue = 0;
                self.slider.value = 1;
                self.sliderValue = 1;
                UIImage *switchThumImg = [UIImage imageNamed:@"Switches"];
                switchThumImg = [switchThumImg scaleToSize:CGSizeMake(42, 28.2)];
                [self.switchSlider setThumbImage:switchThumImg forState:UIControlStateNormal];
                NSString *fourByte = [dataString subStringWithRangeForNil:NSMakeRange(6, 2)];
                if ([fourByte isEqualToString:@"00"]) {
                    // 未报警
                    [self stopShakeSound];
//                    self.overspeadView.hidden = NO;
                    self.shakeView.hidden = YES;
                }
                if ([fourByte isEqualToString:@"01"]) {
                    // 报警中
                    [self startShakeSound];
                    [self shakeViewShow];
                    
//                    self.overspeadView.hidden = NO;
                    self.shakeView.hidden = NO;
                }
            }
        }
        if ([secondByte isEqualToString:@"02"]) {
            // 音量
            // 音量值
            NSString *thirdByte = [dataString subStringWithRangeForNil:NSMakeRange(4, 2)];
            self.voiceValue = [CalculateTool doubleHexToSingleDecimal:thirdByte];
            [self setVoiceImageWithValue:self.voiceValue];
        }
        
        
    }
    if ([firstByte isEqualToString:@"01"]) {
        // FM
        NSString *secondByte = [dataString subStringWithRangeForNil:NSMakeRange(2, 2)];
        if ([secondByte isEqualToString:@"01"]) {
            //播放
            self.outCircleButton.selected = YES;
            self.inCircleButton.selected = NO;            }
        if ([secondByte isEqualToString:@"00"]) {
            //静音
            self.outCircleButton.selected = NO;
            self.inCircleButton.selected = YES;
        }
        
        NSString *thirdAndFourByte = [dataString subStringWithRangeForNil:NSMakeRange(4, 4)];//频率
        self.messageLabel.text = [NSString stringWithFormat:@"%d",[CalculateTool twoDoubleHexToSingleDecimal:thirdAndFourByte]];
        NSString *message = self.messageLabel.text;
        if (self.messageLabel.text.length > 2) {
            self.messageLabel.text = [NSString stringWithFormat:@"%@.%@MHZ",[self.messageLabel.text subStringWithRangeForNil:NSMakeRange(0, message.length-2)],[self.messageLabel.text subStringWithRangeForNil:NSMakeRange(message.length-2, 2)]];
        }
        NSString *fiveByte = [dataString subStringWithRangeForNil:NSMakeRange(8, 2)];//台号
        NSString *sixByte = [dataString subStringWithRangeForNil:NSMakeRange(10, 2)];//台号
        
        
        
    }
    if ([firstByte isEqualToString:@"02"]) {
        NSLog(@"lanya?");
    }
    if ([firstByte isEqualToString:@"03"]) {
        self.outCircleButton.selected = YES;
        self.messageLabel.text = @"";
        self.startTimeLabel.text = @"00:00";
        self.endTimeLabel.text = @"00:00";
    }
    if ([firstByte isEqualToString:@"04"]) {
        NSString *secondByte = [dataString subStringWithRangeForNil:NSMakeRange(2, 2)];
        if ([secondByte isEqualToString:@"01"]) {
            //时间曲目
            NSString *thirdAndFourByte = [dataString subStringWithRangeForNil:NSMakeRange(4, 4)];//曲目号
            //                NSString *fiveAndSixByte = [dataString subStringWithRangeForNil:NSMakeRange(8, 4)];//曲目总数
            NSString *sevenAndEightByte = [dataString subStringWithRangeForNil:NSMakeRange(12, 4)];//播放时间
            NSString *nineAndTenByte = [dataString subStringWithRangeForNil:NSMakeRange(16, 4)];//总时间
            NSString *elevenByte = [dataString subStringWithRangeForNil:NSMakeRange(20, 2)];//播放暂停
            self.currentMusicNumber = [CalculateTool twoDoubleHexToSingleDecimal:thirdAndFourByte];
            
            if ([elevenByte isEqualToString:@"01"]) {
                self.outCircleButton.selected = YES;
                self.inCircleButton.selected = YES;
            }
            if ([elevenByte isEqualToString:@"00"]) {
                [self.timer invalidate];
                self.outCircleButton.selected = NO;
                self.inCircleButton.selected = NO;
            }
            self.startTimeLabel.text = [CalculateTool secondToMiniuteSecondString:[CalculateTool twoDoubleHexToSingleDecimal:sevenAndEightByte]];
            self.endTimeLabel.text = [CalculateTool secondToMiniuteSecondString:[CalculateTool twoDoubleHexToSingleDecimal:nineAndTenByte]];
            self.timeSlider.minimumValue = 0;
            self.timeSlider.maximumValue = [CalculateTool twoDoubleHexToSingleDecimal:nineAndTenByte];
            self.currentMusicTime = [CalculateTool twoDoubleHexToSingleDecimal:sevenAndEightByte];
            [self.timer invalidate];
            if ([elevenByte isEqualToString:@"01"]) {
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(currentMusicHandleTimeEven) userInfo:nil repeats:YES];
            }
            
            
            
            
        }
        if ([secondByte isEqualToString:@"02"]) {
            //                NSString *thirdByte = [dataString subStringWithRangeForNil:NSMakeRange(4, 2)];//编码格式
            NSString *foureByte = [dataString subStringWithRangeForNil:NSMakeRange(6, 2)];
            if ([foureByte isEqualToString:@"01"]) {
                //开始
            }
            [self.currentMusicArray addObject:dataString];
            if ([foureByte isEqualToString:@"00"]) {
                PlayBlueMusicListManager *manager = [[PlayBlueMusicListManager alloc]init];
                NSArray *array = [manager getSongNameFromBlueWithArray:self.currentMusicArray];
                self.messageLabel.text = [array firstObject];
                [self.currentMusicArray removeAllObjects];
                NSLog(@"%@",array);
                //结束
            }
            //歌名
        }
    }
    if ([firstByte isEqualToString:@"05"]) {
        
    }
    if ([firstByte isEqualToString:@"06"]) {
        
    }
    if ([firstByte isEqualToString:@"07"]) {
        NSString *secondByte = [dataString subStringWithRangeForNil:NSMakeRange(2, 2)];
        if ([secondByte isEqualToString:@"01"]) {
            //校验密码
            NSString *thirtBytes = [dataString subStringWithRangeForNil:NSMakeRange(4, 2)];
            if ([thirtBytes isEqualToString:@"00"]) {
                self.password = @"";
                [self textAlertViewSHow:NSLocalizedString(@"enterRightPwd",@"请输入正确的密码") type:1];
                
                
            }
            if ([thirtBytes isEqualToString:@"01"]) {
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:BLE_MAN.peripheral.identifier.UUIDString forKey:UD_FOR_LAST_CONNECTED_IDENTIFI];
                [self savePassword:self.password peripheralName:BLE_MAN.peripheral.name];
                [BLE_MAN sendDataWithCommand:@"0704" withBlock:^(BOOL result, NSString * _Nullable resultStr) {
                    
                }];
            }
        }
        if ([secondByte isEqualToString:@"02"]) {
            //修改密码
            NSString *thirtBytes = [dataString subStringWithRangeForNil:NSMakeRange(4, 2)];
            if ([thirtBytes isEqualToString:@"00"]) {
                //修改失败
                [self showInfoMessage:NSLocalizedString(@"changePwdFail",@"修改密码失败")];
            }
            if ([thirtBytes isEqualToString:@"01"]) {
                //修改成功
                [self tipsAlertSelectViewSHow:NSLocalizedString(@"passwordChanged", @"密码已改变，是否保存？") peripheralName:BLE_MAN.peripheral.name];
                //                    [self showInfoMessage:NSLocalizedString(@"changePwdSuccess",@"修改密码成功")];
                
                
            }
            
        }
        if ([secondByte isEqualToString:@"03"]) {
            //手动获取BLE地址
        }
    }
    
}

- (void)setSliderValue:(NSInteger)sliderValue {
    _sliderValue = sliderValue;
    if (sliderValue == 0) {
        self.switchSliderProtectionBtn.hidden = NO;
    }else {
        self.switchSliderProtectionBtn.hidden = YES;
    }
}

- (void)setSwitchSliderValue:(CGFloat)switchSliderValue {
    _switchSliderValue = switchSliderValue;
    if (switchSliderValue == 0) {
        self.overspeadView.hidden = NO;

        self.sliderPretetionBtn.hidden = YES;
    }else {
        self.sliderPretetionBtn.hidden = NO;
        self.overspeadView.hidden = YES;

    }
}

@end
